package com.nowcoder.community.controller;

import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
public class LoginController implements CommunityConstant {
    @Autowired
    private UserService userService;
    @Value("server.servlet.context-path")
    private String contextPath;
    //访问注册页面
    @RequestMapping(path = "/register",method = RequestMethod.GET)
    public String getRegister(){
        return "/site/register";
    }

    //接收注册数据，发送激活邮件
    @RequestMapping(path = "/register",method = RequestMethod.POST)
    public String register(User user, Model model){
        Map<String,Object> map = userService.register(user);
        //没问题
        if(map.isEmpty()||map==null){
            model.addAttribute("Msg","注册成功，我们已经向您的邮箱发送了一封激活邮件，请尽快前往激活！");
            model.addAttribute("target","/index");
            return "site/operate-result";
        }
        //有问题
        else{
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            model.addAttribute("emailMsg",map.get("emailMsg"));
            return "site/register";
        }
    }

    //激活用户
    // http://localhost:8080/community/activation/id/code
    @RequestMapping(path = "/activation/{userId}/{activationCode}",method = RequestMethod.GET)
    public String activation(Model model,@PathVariable("userId")int userId,@PathVariable("activationCode")String code){
        int result = userService.activation(userId, code);
        if(result==ACTIVATION_REPEAT){
            model.addAttribute("Msg","无效操作，您已激活该账户，不需要重新激活。");
            model.addAttribute("target", "/index");
        }else if(result==ACTIVATION_SUCCESS){
            model.addAttribute("Msg","激活成功,您的账号已经可以正常使用了!");
            model.addAttribute("target", "/login");
        }else{
            model.addAttribute("Msg","激活失败,您提供的激活码不正确!");
            model.addAttribute("target", "/index");
        }
        return "/site/operate-result";
    }

    //访问登陆页面
    @RequestMapping(path = "/login",method = RequestMethod.GET)
    public String getLogin(){
        return "/site/login";
    }

    //异步返回错误信息
    @RequestMapping(path="/register/error",method = RequestMethod.POST)
    @ResponseBody
    public String registerError(User user){
        //看用户名是否重复
        String username=user.getUsername();
        User u = userService.findUserByName(username);
        if(u!=null){
            return CommunityUtil.getJSONString(0,"该名称已被占用");
        }else{
            return CommunityUtil.getJSONString(1,"该名称尚未被使用");
        }
    }

    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public String login(String username, String password, String code, boolean rememberme,
                        Model model, HttpServletResponse response/*,
                        @CookieValue("kaptchaOwner") String kaptchaOwner*/) {
//        // 检查验证码
////        String kaptcha = (String) session.getAttribute("kaptcha");
//        String kaptcha = null;
//        if(StringUtils.isNotBlank(kaptchaOwner)){
//            String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
//            kaptcha = (String)redisTemplate.opsForValue().get(redisKey);
//        }
//        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)) {
//            model.addAttribute("codeMsg", "验证码不正确!");
//            return "/site/login";
//        }

        // 检查账号,密码
        int expiredSeconds = rememberme ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        if (map.containsKey("ticket")) {
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);
            return "redirect:/index";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "/site/login";
        }
    }

    @RequestMapping(path = "/logout", method = RequestMethod.GET)
    public String logout(@CookieValue("ticket") String ticket) {
        userService.logout(ticket);
        return "redirect:/login";
    }
}
